package com.ldn.starter.aspect;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import com.ldn.basic.dispose.annotation.RequestLimit;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author 李大牛家的牛 (scafel@163.com)
 * @createDate 2024/7/9 - 16:55
 * @description ...
 **/
@Slf4j
@Aspect
@Component
public class RequestLimitAspect {

    private final Map<String, RateLimiter> limitMap = Maps.newConcurrentMap();

    @Around("@annotation(com.ldn.basic.dispose.annotation.RequestLimit)")
    public Object around(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //拿limit的注解
        RequestLimit limit = method.getAnnotation(RequestLimit.class);
        if (limit != null) {
            //key作用：不同的接口，不同的流量控制
            String key=limit.key();
            RateLimiter rateLimiter = null;
            //验证缓存是否有命中key
            if (!limitMap.containsKey(key)) {
                // 创建令牌桶
                rateLimiter = RateLimiter.create(limit.permitsPerSecond());
                limitMap.put(key, rateLimiter);
                log.info("新建了令牌桶={}，容量={}",key,limit.permitsPerSecond());
            }
            rateLimiter = limitMap.get(key);
            // 拿令牌
            boolean acquire = rateLimiter.tryAcquire(limit.timeout(), limit.timeunit());
            // 拿不到命令，直接返回异常提示
            if (!acquire) {
                log.debug("RequestLimitAspect 令牌桶={}，获取令牌失败",key);
                this.responseFail("获取令牌失败");
                return null;
            }
        }
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            this.responseFail(e.getMessage());
            return null;
        }
    }

    /**
     * 直接向前端抛出异常
     * @param msg 提示信息
     */
    private void responseFail(String msg)  {
        throw new RuntimeException(msg);
    }

}
